package springbook.user.dao;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

import springbook.common.ConnectionMaker;
import springbook.common.DConnect;
//import springbook.common.SimpleConnectionMaker;
import springbook.user.domain.*;

public abstract class UserDao {

	private ConnectionMaker connectionMaker;
	
	public UserDao(){
		connectionMaker = new DConnect();
	}
	
	public void add(User user) throws ClassNotFoundException, SQLException{

		Connection c = (Connection) connectionMaker.makeConnection();
		
		String strSql = "insert into users(id, name, password) values(?,?,?)";
		
		PreparedStatement ps = (PreparedStatement) c.prepareStatement(strSql);
		
		int col = 1;
		
		ps.setString(col++, user.getId());
		ps.setString(col++, user.getName());
		ps.setString(col++, user.getPassword());
		
		ps.executeUpdate();
		
		ps.close();
		c.close();
	}
	
	public User get(String id) throws ClassNotFoundException, SQLException{
		
		Connection c = (Connection) connectionMaker.makeConnection();
		
		String strSql = "select * from users where id = ?";
		
		PreparedStatement ps = (PreparedStatement) c.prepareStatement(strSql);
		
		int col = 1;
		
		ps.setString(col, id);
		
		ResultSet rs = ps.executeQuery();
		
		rs.next();
		
		User user = new User();
		user.setId(rs.getString("id"));
		user.setName(rs.getString("name"));
		user.setPassword(rs.getString("password"));
		
		rs.close();
		ps.close();
		c.close();
		
		return user;
	}
	
	public abstract Connection getConnection() throws ClassNotFoundException, SQLException;
}
